package com.pm.main.infrastructure.product;

import com.pm.main.common.PageRepository;
import com.pm.main.common.PageRsp;
import com.pm.main.controller.req.CommoditySearchReq;
import com.pm.main.controller.rsp.HotCommodityRsp;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import reactor.core.publisher.Flux;
import com.pm.main.common.PageReq;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.function.Function;

/**
 * Created by cjwfuture on 2021/6/6
 */

@Repository
public class ProductRepository {
    @Resource
    private ReactiveMongoTemplate reactiveMongoTemplate;

    public Function<PageReq, Pageable> getPageMapper() {
        return a -> PageRequest.of(a.getPage(), a.getSize());
    }

    public Flux<HotCommodityRsp> listOfHot(@RequestBody CommoditySearchReq searchReq) {
        Query query = new Query().with(getPageMapper().apply(searchReq));
        if (!CollectionUtils.isEmpty(searchReq.getIds())) {
            query.addCriteria(Criteria.where("id").in(searchReq.getIds()));
        }
        if (StringUtils.hasText(searchReq.getKw())) {
            query.addCriteria(Criteria.where("name").regex(".*?" + searchReq.getKw() + ".*"));
        }
        return reactiveMongoTemplate.find(query, ProductPO.class).map(a -> {
            HotCommodityRsp rsp = new HotCommodityRsp();
            rsp.setPrice(a.getCostPrice());
            rsp.setName(a.getName());
            rsp.setShowImage(CollectionUtils.isEmpty(a.getImages())
                    ? "https://t00img-c.yangkeduo.com/goods/images/2021-05-27/0ee7a4525bc5e5ce72a04f7503a5a65d.jpeg"
                    : a.getImages().get(0));
            return rsp;
        });
    }


    public Mono<ProductPO> add(ProductPO productPO){
        return reactiveMongoTemplate.insert(productPO);
    }


}
